package com.beichuan_travel.interceptor;

import com.beichuan_travel.enums.ResultCode;
import com.beichuan_travel.model.vo.ResultVO;
import com.beichuan_travel.utils.JwtManager;
import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    JwtManager jwtManager;

    public LoginInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if ("user/login".equals(request.getRequestURI())) {
//            return true;
//        }
        if (true) {
            return true;
        }

        Claims claims = jwtManager.parse(request.getHeader("token"));
        if (claims != null) {
            long life = System.currentTimeMillis() - claims.getIssuedAt().getTime();
            if (life > (claims.getExpiration().getTime() - claims.getIssuedAt().getTime()) / 2) {
                System.out.println(life);
                response.setHeader("token", jwtManager.generate(claims.getSubject()));
            }
            return true;
        }

        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        ResultVO<String> vo = new ResultVO<>(ResultCode.UNAUTHORIZED);
        writer.write(vo.toString());
        writer.flush();
        writer.close();
        return false;
    }
}
